<template>
    <Dialog :app-dialog="appDialog" @closed="closedDialog">
        <el-scrollbar class="tag_bars upload-video" max-height="600px">
            <el-form ref="formRef" :model="form" :rules="rules" label-width="110px">
                <!-- 分组 -->
                <el-form-item label="分组">
                    <el-cascader
                        ref="cascaderRef"
                        v-model="form.group"
                        style="width: 100%"
                        :options="groupData"
                        :props="defaultProps"
                        placeholder="请选择分组"
                        @change="orgChange" />
                </el-form-item>
                <!-- 类型 -->
                <el-form-item label="类型" class="form-radio">
                    <el-radio-group v-model="form.type" class="radio_list" @change="changeType">
                        <el-radio
                            v-for="item in typeDiff"
                            :key="item.value"
                            :label="item.value"
                            class="radio_list_item">
                            <span class="radio_list_item_text">{{ item.name }}</span>
                            <el-tooltip v-if="item.value === 1" :content="item.text" placement="bottom">
                                <div class="radio_list_item_icon radio_img">
                                    <img src="@/assets/image/material/question.png" alt="" />
                                </div>
                            </el-tooltip>
                        </el-radio>
                    </el-radio-group>
                </el-form-item>
                <!-- 上传文件 -->
                <ZWUpload ref="UploadData" @submit="getFileList" />
                <el-form-item>
                    <template #label>
                        <div class="label_text">
                            <span>素材标签</span>
                            <el-tooltip :content="tagTips.materialTagTips" placement="top">
                                <img src="@/assets/image/material/question.png" alt="" />
                            </el-tooltip>
                        </div>
                    </template>
                    <selectTags ref="tagIdsRef" v-model="form.tag_ids" />
                </el-form-item>
                <el-form-item v-if="form.type == 1" label="是否强制授权">
                    <el-radio-group v-model="form.is_force_grant" @change="changeAuth">
                        <el-radio :label="1">否</el-radio>
                        <el-radio :label="2">是</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item v-show="form.is_force_grant == 2 && form.type == 1" label="授权内容">
                    <el-checkbox-group v-model="form.grant_params">
                        <el-checkbox label="offical_headimg_nickname">头像昵称（公众号）</el-checkbox>
                        <el-checkbox label="phone">手机号（小程序）</el-checkbox>
                    </el-checkbox-group>
                </el-form-item>

                <el-form-item v-if="form.type == 1">
                    <template #label>
                        <div class="label_text">
                            <span>浏览打标</span>
                            <el-tooltip :content="tagTips.browseCustTips" placement="top">
                                <img src="@/assets/image/material/question.png" alt="" />
                            </el-tooltip>
                        </div>
                    </template>
                    <selectTags ref="viewtagIdsRef" v-model="form.view_tag_ids" :type="2" />
                </el-form-item>
                <el-form-item v-if="form.type == 1">
                    <template #label>
                        <div class="label_text">
                            <span>分享打标</span>
                            <el-tooltip :content="tagTips.shareCustTips" placement="top">
                                <img src="@/assets/image/material/question.png" alt="" />
                            </el-tooltip>
                        </div>
                    </template>
                    <selectTags ref="shareTagIdsRef" v-model="form.share_tag_ids" :type="2" />
                </el-form-item>
            </el-form>
        </el-scrollbar>
    </Dialog>
</template>
<script setup lang="ts">
import { ref, reactive, computed, watch, onUnmounted, onMounted } from 'vue';
import Dialog from '@/components/Dialog.vue';
import ZWUpload from './ZWUpload.vue';
import selectTags from '../../../components/selectTags.vue';
import { conserve, getVideoData, updateVideo, getGroupList } from '@/api/concreation';
import { ElForm, ElMessage } from 'element-plus';
import { getSetionId } from '@/utils/utils';
import { endLoading, startLoading } from '@/utils/request';

const props = defineProps(['groupId', 'type']);
const emit = defineEmits(['submit', 'closed']);
import bus from '@/utils/bus';

const formRef = ref<InstanceType<typeof ElForm>>();
const cascaderRef: any = ref(null); // 选择分组ref
type FormInstance = InstanceType<typeof ElForm>;

import { useStore } from '@/store';
const store = useStore();
const uploadSelectRef = ref(null);
const uploadTitle = ref('上传文件');
const uploadVisib = ref(false);
const UploadData = ref(false);
const isEdit = ref(false);
const tagType = ref(1);
const tagIdsRef = ref(null);
const viewtagIdsRef = ref(null);
const shareTagIdsRef = ref(null);
const tagTips = {
    materialTagTips: '该素材会被打上此素材标签，在列表上会展示',
    browseCustTips: '浏览该素材的客户将被打上此客户标签',
    shareCustTips: '点击该素材的分享按钮并生成分享链接的客户将被打上此客户标签'
};

//上传弹框
const uploadInfo = computed(() => {
    return store.getters['content/upload'];
});
// 1-文本 2-图片 3-音频 4-视频 5-文件 6-链接文章 7-链接引用
// 分组列表
const groupData = ref([]);

/**
 * @description: 获取分组数据
 * @return {*}
 */
const getGroupListFunc = async () => {
    const res = await getGroupList({ type: props.type });
    groupData.value = res.data;
};
//标签
const tags = computed(() => {
    return store.getters['content/tagsInfo'].tags;
});
const defaultProps = {
    checkStrictly: true,
    emitPath: false,
    label: 'name',
    value: 'id'
};
const form = reactive({
    tag_ids: [],
    view_tag_ids: [],
    is_force_grant: 1,
    group: 0, //分组
    type: 0,
    video: '', // 音频文件
    tags: [], //标签
    check: true, //用户协议
    title: '', //标题
    id: '', //内容id
    share_tag_ids: [],
    grant_params: ['offical_headimg_nickname', 'phone']
});

const changeType = (val: any) => {
    if (val == 0) {
        form.is_force_grant = '';
    } else if (val == 1) {
        form.is_force_grant = 1;
    }
};

const rules = reactive({
    title: [
        {
            required: true,
            message: '标题不能为空',
            trigger: 'blur'
        }
    ],
    video: [
        {
            required: true,
            message: '视频不能为空',
            trigger: ['change', 'blur']
        }
    ]
});
const typeDiff = reactive([
    { value: 0, name: `普通视频` },
    {
        value: 1,
        name: `雷达视频`,
        text: `雷达视频可以追踪客户端浏览次数、时间等数据`
    }
]);
// 获取上传成功的文件
const getFileList = (data: any) => {
    try {
        if (data.length) {
            const video = getSetionId('code', data);
            form.video = video[0];
        } else {
            form.video = '';
        }
    } catch (error) {
    } finally {
        endLoading();
    }
};
const changeAuth = () => {
    if (form.is_force_grant == 1) {
        form.grant_params = [];
    } else {
        form.grant_params = ['offical_headimg_nickname', 'phone'];
    }
};
// 取消
const cancelHandel = () => {
    appDialog.visible = false;
    isEdit.value = false;
    form.group = 0;
    form.type = 0;
    form.code = '';
    form.title = '';
    form.tags = [];
    form.id = '';
    UploadData.value.uploadFileList = [];
    formRef.value.resetFields();
};
//确定
const submitHandel = () => {
    formRef.value.validate(async (valid: any) => {
        const groupId = form.group;
        if (valid) {
            const grant = {
                offical_headimg_nickname: form.grant_params.includes('offical_headimg_nickname') ? 2 : 1,
                phone: form.grant_params.includes('phone') ? 2 : 1
            };
            const params = {
                // title: form.title,
                group_id: form.group,
                file_type: form.type,
                code: form.video,
                tag_ids: getSetionId('id', form.tag_ids),
                view_tag_ids: getSetionId('id', form.view_tag_ids),
                media_content_id: form.id,
                is_force_grant: form.is_force_grant,
                grant_params: grant,
                share_tag_ids: getSetionId('id', form.share_tag_ids)
            };
            if (form.type === 0) {
                delete params.view_tag_ids;
                delete params.share_tag_ids;
            }
            isEdit.value ? (params.media_content_id = form.id) : '';
            try {
                startLoading();
                isEdit.value ? await updateVideo(params) : await conserve(params);
                cancelHandel();
                emit('submit', { id: groupId });
            } catch (error) {
                // console.log(error)
                endLoading();
            }
        }
    });
};
const appDialog = reactive({
    visible: uploadVisib,
    title: uploadTitle,
    width: '670px',
    cancel: cancelHandel,
    submit: submitHandel,
    isDisable: false,
    cancelText: '取消',
    submitText: '保存'
});
//获取编辑内容
const editItem = (data: any) => {
    isEdit.value = true;
    // UploadData.value.uploadFileList=[]
    getVideoData({ media_content_id: data.id }).then((res: any) => {
        // tag_ids 素材标签
        // view_tag_ids 浏览客户标签
        // share_tag_ids 分享客户标签
        form.tag_ids = res.tag_info;
        form.view_tag_ids = res.view_tag_info;
        form.share_tag_ids = res.share_tag_info;
        form.title = res.title;
        form.group = res.group_id;
        form.tags = res.tag_info;
        form.type = res.is_radar;
        form.video = res.media_content_media?.media_file?.code;
        form.id = res.id;
        form.is_force_grant = res.is_force_grant;
        form.grant_params = [];
        if (res.grant_params?.offical_headimg_nickname == 2) {
            form.grant_params.push('offical_headimg_nickname');
        }
        if (res.grant_params?.phone == 2) {
            form.grant_params.push('phone');
        }
        UploadData.value.uploadFileList = [
            {
                url: res.media_content_media?.url,
                code: res.media_content_media?.media_file?.code,
                name: res.media_content_media?.media_file?.name
            }
        ];
        setTimeout(() => {
            tagIdsRef.value?.init();
            viewtagIdsRef.value?.init();
            shareTagIdsRef.value?.init();
        }, 0);
    });
};
bus.on('editItem', editItem);
watch(uploadInfo, uploadInfo => {
    uploadTitle.value = uploadInfo.title;
    form.grant_params = ['offical_headimg_nickname', 'phone'];
    form.is_force_grant = 1;
    form.type = 0;
    form.check = true;
});
watch(tags, data => (form.tags = data));
watch(
    () => props.groupId,
    val => {
        form.group = val;
    },
    { immediate: true }
);
watch(
    () => form.video,
    () => formRef.value.validateField('video')
);

const closedDialog = () => {
    emit('closed');
};
// 选择完地区后立即关闭
const orgChange = () => {
    cascaderRef.value.togglePopperVisible();
};
onUnmounted(() => {
    bus.off('editItem', editItem);
});

onMounted(() => {
    getGroupListFunc();
});

defineExpose({
    uploadVisib,
    uploadTitle
});
</script>

<style lang="scss" scoped>
.upload-video {
    padding-top: 14px;

    .form-radio {
        line-height: normal;

        :deep(.el-form-item__label),
        :deep(.el-form-item__content) {
            line-height: normal;
        }

        .el-radio {
            height: auto;
        }
    }
}

.radio_list {
    &_item {
        &_icon {
            width: 14px;
            height: 14px;
            margin: -3px 0 0 6px;

            img {
                margin-top: 2px;
                width: 100%;
                height: 100%;
                vertical-align: top;
            }
        }
    }

    :deep .el-radio__label {
        display: flex;
        align-items: center;
    }
}

.ml2 {
    margin-left: 2px;
}

.mr10 {
    margin-right: 10px;
}

.agree_ment {
    display: flex;
    align-items: center;
}

:deep .tag_bars {
    height: auto;
}

:deep(.el-form-item) {
    .label_text {
        display: flex;
        align-items: center;
        gap: 6px;

        img {
            width: 14px;
            height: 14px;
        }
    }
}
</style>
